package com.wyy.todo.resolver;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyy.todo.beans.PageInfo;
import com.wyy.todo.beans.Schedules;
import com.wyy.todo.beans.SchedulesVo;
import com.wyy.todo.dao.SchedulesInputDao;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.wyy.todo.constants.SchedulesConstants.*;

@Service
public class SchedulesQueryResolver implements GraphQLQueryResolver {

    @Autowired
    private SchedulesInputDao schedulesInputDao;

    public PageInfo<SchedulesVo> findAll(Integer pageNumber, Integer pageSize, Integer status) {
        // 根据分页条件查询数据
        Page<Schedules> todoPage = getDataByPageAndStatus(pageNumber, pageSize, status);
        // 构建 SchedulesVoList
        List<SchedulesVo> schedulesVoList = getSchedulesVoList(todoPage.getRecords());
        // 返回部分代码
        return getPageInfo(schedulesVoList,todoPage,status);
    }


    private PageInfo<SchedulesVo> getPageInfo(List<SchedulesVo> schedulesVoList, Page<Schedules> todoPage, Integer status) {
        return PageInfo.<SchedulesVo>builder()
                .data(schedulesVoList)
                .status(ObjectUtils.isEmpty(status) ? SCHEDULES_STATUS_VAL_ALL : status)
                .current(todoPage.getCurrent())
                .size(todoPage.getSize())
                .total(todoPage.getTotal())
                .build();
    }


    private List<SchedulesVo> getSchedulesVoList(List<Schedules> records) {
        if(ObjectUtils.isEmpty(records)) {
            return Collections.emptyList();
        }

        return records.stream()
                .map(schedules -> SchedulesVo.builder()
                        .data(schedules.getData())
                        .status(schedules.getStatus())
                        .id(schedules.getId())
                        .build()).collect(Collectors.toList());
    }


    private Page<Schedules> getDataByPageAndStatus(Integer pageNumber, Integer pageSize, Integer status) {
        Page<Schedules> page = new Page<>(pageNumber, pageSize);
        QueryWrapper<Schedules> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(!ObjectUtils.isEmpty(status), SCHEDULES_STATUS, status);
        queryWrapper.orderByDesc(SCHEDULES_CREATE_TIME);
        return schedulesInputDao.selectPage(page, queryWrapper);
    }
}
